<?php
// 各种授权，token，令牌的获取

namespace JyWxThird\Init\Open;

use JyWxThird\Kernel\Http;

trait Token
{
  /**
   * 获取令牌 component_access_token
   * 令牌是第三方平台接口的调用凭据。令牌的获取是有限制的，有效期为 2 小时，请自行做好，在快过期时（比如1小时50分），重新调用接口获取。
   * https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/token/component_access_token.html
   *
   * @param $component_verify_ticket
   * @return false|mixed
   */
  public function get_component_access_token($component_verify_ticket)
  {
    $param = [
      'component_appid'         => $this->config['appid'],
      'component_appsecret'     => $this->config['secret'],
      'component_verify_ticket' => $component_verify_ticket,
    ];
    $res   = Http::httpPostJson($this->domainUrl . '/cgi-bin/component/api_component_token', $param);
    if (isset($res['component_access_token'])) {
      return $res;
    }
    $this->setError($res);
    return false;
  }
  
  /**
   * 获取/刷新接口调用令牌
   * https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/token/api_authorizer_token.html
   *
   * @param string $component_access_token   第三方平台component_access_token
   * @param string $authorizer_appid         授权方 appid
   * @param string $authorizer_refresh_token 刷新令牌，获取授权信息时得到
   * @return false|mixed
   */
  public function refresh_authorizer_access_token($component_access_token, $authorizer_appid, $authorizer_refresh_token)
  {
    $param = [
      'component_appid'          => $this->config['appid'],
      'authorizer_appid'         => $authorizer_appid,
      'authorizer_refresh_token' => $authorizer_refresh_token,
    ];
    $res   = Http::httpPostJson($this->domainUrl . '/cgi-bin/component/api_authorizer_token?component_access_token=' . $component_access_token, $param);
    if (isset($res['authorizer_access_token'])) {
      return $res;
    }
    $this->setError($res);
    return false;
  }
  
  /**
   * 获取预授权码
   *
   * @param string $component_access_token
   */
  public function get_pre_auth_code($component_access_token)
  {
    $param = [
      'component_appid' => $this->config['appid'],
    ];
    $res   = Http::httpPostJson($this->domainUrl . '/cgi-bin/component/api_create_preauthcode?component_access_token=' . $component_access_token, $param);
    if (isset($res['pre_auth_code'])) {
      return $res;
    }
    $this->setError($res);
    return false;
  }
}
